import { routerRedux } from "dva/router";
import { stringify } from "qs";
import { login, info, changeTenant, getSmsCaptcha } from "@/services/user";
import { setAuthority } from "@/utils/authority";
import { getPageQuery } from "@/utils/utils";
import { reloadAuthorized } from "@/utils/Authorized";
import MenuPath from "@/utils/menuPath";
import { qywxLogin } from "@/services/qywx";
import UserSession from "@/UserSession";
import { loginAuth, sso } from "@/services/aigcUser";

export default {
	namespace: "login",
	state: {
		status: undefined,
		token: {},
		currentUser: {},
		loading: true,
	},
	effects: {
		*login({ payload, callback }, { call, put }) {
			const response = yield call(login, payload);
      //1.若只有一个租户 则直接进入后台
      //2.若有多个租户 则进入租户选择页 选择登录
      // if(response.length == 1){
      //   const data = response[0]
      //   yield put({
			// 		type: "loginToTenant",
			// 		payload: {id:data.id,username:data.nick,tenantId:data.tenantId,type:data.type,path:data.path},
			// 	});
      // }else{
      //   callback(response);
      // }
      callback(response);
      
		},

		*getSmsCaptcha({ payload, callback }, { call, put }) {
			const response = yield call(getSmsCaptcha, payload);
      callback(response);
		},

    *loginBySSO({ payload, callback }, { call, put }) {
			const response = yield call(sso, payload);
      //1.若只有一个租户 则直接进入后台
      //2.若有多个租户 则进入租户选择页 选择登录
      // if(response.length == 1){
      //   const data = response[0]
      //   yield put({
			// 		type: "loginToTenant",
			// 		payload: {id:data.id,username:data.nick,tenantId:data.tenantId,type:data.type,path:data.path},
			// 	});
      // }else{
      //   callback(response);
      // }
      callback(response);
		},
		*logout(_, { put }) {
			yield put({
				type: "changeLoginStatus",
				payload: {
					status: false,
					roles: ["guest"],
				},
			});
			window.localStorage.clear();
			reloadAuthorized();
			// redirect
			if (window.location.pathname !== "/user/login") {
				yield put(
					routerRedux.replace({
						pathname: "/user/login",
						search: stringify({
							redirect: "",
						}),
					})
				);
			}
		},
		*changeTenantByClick({ payload, callback }, { call, put }) {
			const response = yield call(changeTenant, payload);
			if (response.data) {
				// Login successfully
				const response1 = yield call(info, {});
				yield put({
					type: "saveAuthMenu",
					payload: response1.menus,
				});
				if (response1) {
					reloadAuthorized();
					window.localStorage.setItem("currentUser", JSON.stringify(response1));
					const urlParams = new URL(window.location.href);
					const params = getPageQuery();
					let { redirect } = params;
					if (redirect) {
						const redirectUrlParams = new URL(redirect);
						if (redirectUrlParams.origin === urlParams.origin) {
							redirect = redirect.substr(urlParams.origin.length);
							if (redirect.startsWith("/#")) {
								redirect = redirect.substr(2);
							}
						} else {
							window.location.href = redirect;
							return;
						}
					}

					window.history.pushState(null, null, "/");
					window.location.reload();
				}
			} else {
				callback(response);
			}
		},
		*loginByQywx({ payload, callback }, { call, put }) {
			const response = yield call(qywxLogin, payload);
			window.localStorage.setItem("robot_token", response.data);
			yield put({
				type: "changeLoginStatus",
				payload: response.data,
			});
			const response1 = yield call(info, {});

			yield put({
				type: "saveAuthMenu",
				payload: response1.menus,
			});
			if (response1) {
				reloadAuthorized();
				window.localStorage.setItem("currentUser", JSON.stringify(response1));
				const urlParams = new URL(window.location.href);
				const params = getPageQuery();
				let { redirect } = params;
				if (redirect) {
					const redirectUrlParams = new URL(redirect);
					if (redirectUrlParams.origin === urlParams.origin) {
						redirect = redirect.substr(urlParams.origin.length);
						if (redirect.startsWith("/#")) {
							redirect = redirect.substr(2);
						}
					} else {
						window.location.href = redirect;
						return;
					}
				}
				let path = "/";
				yield put(routerRedux.replace(redirect || path));
			}
		},
    *loginToTenant({ payload, callback }, { call, put }) {
			const response = yield call(loginAuth, payload);
			if (response.data) {
				// Login successfully
				window.localStorage.setItem("robot_token", response.data);
				yield put({
					type: "changeLoginStatus",
					payload: response.data,
				});
				const response1 = yield call(info, {});
				// 超级管理员没有首页
				if (response1.tenantId != '1') {
					response1.menus = { ...response1.menus }
				}

				yield put({
					type: "saveAuthMenu",
					payload: response1.menus,
				});
				if (response1) {
					reloadAuthorized();
					window.localStorage.setItem("currentUser", JSON.stringify(response1));
					const urlParams = new URL(window.location.href);
					const params = getPageQuery();
					let { redirect } = params;
					if (redirect) {
						const redirectUrlParams = new URL(redirect);
						if (redirectUrlParams.origin === urlParams.origin) {
							redirect = redirect.substr(urlParams.origin.length);
							if (redirect.startsWith("/#")) {
								redirect = redirect.substr(2);
							}
						} else {
							window.location.href = redirect;
							return;
						}
					}
					let path = "/";

					yield put(routerRedux.replace(redirect || path));
				}
			} else {
				callback(response);
			}
		},
	},

	reducers: {
		changeLoginStatus(state, { payload }) {
			return {
				...state,
				token: payload,
				loading: false,
			};
		},
		saveAuth(state, { payload }) {
			const activeMent = UserSession.getActiveMenu();
			const menu = UserSession.getSystemMenu();
			setAuthority(menu[activeMent]);
			return {
				...state,
				...payload,
			};
		},
		saveAuthMenu(state, { payload }) {
			let arr = [];
			for (const key in payload) {
				if (payload[key].length) {
					arr.push(key);
				}
			};
			let menu = {};
			let activeMenu = arr[0];
			if (arr.indexOf("interactCenter") != -1) {
				activeMenu = arr[arr.indexOf("interactCenter")]
			} else if (arr.indexOf("homeCenter") != -1) {
				activeMenu = arr[arr.indexOf("homeCenter")]
			};
			UserSession.setSystemMenu(JSON.stringify(payload));
			UserSession.setActiveMenu(activeMenu);
			setAuthority(payload[activeMenu]);
			return {
				...state,
				...payload,
			};
		},
	},
};
